﻿$(function () {
  var Romantics = {};

  Romantics.GridManager = {};
  var tinymcePlugins = [
    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons template textcolor paste textcolor"
  ];
  var tinymceStyleFormats = [
    { title: 'Bold text', inline: 'b' },
    { title: 'Red text', inline: 'span', styles: { color: '#ff0000' } },
    { title: 'Red header', block: 'h1', styles: { color: '#ff0000' } },
    { title: 'Example 1', inline: 'span', classes: 'example1' },
    { title: 'Example 2', inline: 'span', classes: 'example2' },
    { title: 'Table styles' },
    { title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
  ];
  var tinymceToolbar1 = "newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect";
  var tinymceToolbar2 = "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | inserttime preview | forecolor backcolor";
  var tinymceToolbar3 = "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft";
  var tinymceSettings = {
      selector: "#ShortDescription",
      plugins: tinymcePlugins,

      toolbar1: tinymceToolbar1,
      toolbar2: tinymceToolbar2,
      toolbar3: tinymceToolbar3,

      menubar: false,
      toolbar_items_size: 'small',

      style_formats: tinymceStyleFormats

  };
  tinymce.EditorManager.init(tinymceSettings);

  //************************* HIKES GRID
  Romantics.GridManager.hikesGrid = function (gridName, pagerName) {

    //*** Event handlers
    var afterclickPgButtons = function (whichbutton, formid, rowid) {
      tinymce.get("ShortDescription").setContent(formid[0]["ShortDescription"].value);
      tinymce.get("Description").setContent(formid[0]["Description"].value);
    };

    var afterShowForm = function (form) {
      $("#StartDate").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm-dd" });
      $("#StartDate").datepicker($.datepicker.regional["ru"]);
      $("#EndDate").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm-dd" });
      $("#EndDate").datepicker($.datepicker.regional["ru"]);
      tinymce.EditorManager.execCommand('mceAddEditor', true, "ShortDescription");
      tinymce.EditorManager.execCommand('mceAddEditor', false, "Description");

    };

    var onClose = function (form) {
      tinymce.EditorManager.execCommand('mceRemoveEditor', false, "ShortDescription");
      tinymce.EditorManager.execCommand('mceRemoveEditor', false, "Description");
    };

    var beforeSubmitHandler = function (postdata, form) {
      var selRowData = $(gridName).getRowData($(gridName).getGridParam('selrow'));
      if (selRowData["StartDate"])
          postdata.StartDate = selRowData["StartDate"];
      if (selRowData["EndDate"])
          postdata.StartDate = selRowData["EndDate"];
      postdata.ShortDescription = tinymce.get("ShortDescription").getContent();
      postdata.Description = tinymce.get("Description").getContent();

      return [true];
    };

    var colNames = [
        'Идентификатор',
        'Имя',
        'Начало',
        'Окончание',
        'Маршрут',
        'Категория',
        'Категория',
        'Регион',
        'Регион',
        'Опубликован',
        'Краткое Описание',
        'Описание',
        'Ключевые слова'
    ];

    var columns = [];

    columns.push({
      name: 'ID',
      hidden: true,
      key: true
    });

    columns.push({
      name: 'Name',
      index: 'Name',
      width: 250,
      editable: true,
      editoptions: {
        size: 43,
        maxlength: 200
      },
      editrules: {
        required: true
      }
    });

    columns.push({
        name: 'StartDate',
        index: 'StartDate',
        width: 150,
        align: 'center',
        sorttype: 'date',
        datefmt: 'YYYY-MM-DD',
        editable: true,
        editoptions: {
            size: 43,
            maxlength: 200
        },
        editrules: {
            required: true
        },
        search:false
    });

    columns.push({
        name: 'EndDate',
        index: 'EndDate',
        width: 150,
        align: 'center',
        sorttype: 'date',
        datefmt: 'YYYY-MM-DD',
        editable: true,
        editoptions: {
            size: 43,
            maxlength: 200
        },
        editrules: {
            required: true
        },
        search: false
    });

    columns.push({
        name: 'Route',
        index: 'Route',
        width: 250,
        editable: true,
        sortable: false,
        edittype: 'textarea',
        editoptions: {
            rows: "10",
            cols: "100"
        },
        search: false
    });

    columns.push({
      name: 'Category.ID',
      hidden: true,
      editable: true,
      edittype: 'select',
      editoptions: {
          style: 'width:240px;',
          class: "FormElement ui-widget-content ui-corner-all",
          dataUrl: './Admin/GetCategoriesHtml'
      },
      editrules: {
        required: true,
        edithidden: true
      }
    });

    columns.push({
      name: 'Category.Name',
      index: 'Category',
      width: 150
    });

    columns.push({
        name: 'Region.ID',
        hidden: true,
        editable: true,
        edittype: 'select',
        editoptions: {
            style: 'width:240px;',
            class: "FormElement ui-widget-content ui-corner-all",
            dataUrl: './Admin/GetRegionsHtml'
        },
        editrules: {
            required: true,
            edithidden: true
        }
    });

    columns.push({
        name: 'Region.Name',
        index: 'Region',
        width: 150
    });

    columns.push({
      name: 'Published',
      index: 'Published',
      width: 100,
      align: 'center',
      editable: true,
      edittype: 'checkbox',
      editoptions: {
        value: "true:false",
        defaultValue: 'false'
      },
      search: false
    });

    columns.push({
        name: 'ShortDescription',
        index: 'ShortDescription',
        width: 250,
        editable: true,
        sortable: false,
        hidden: true,
        edittype: 'textarea',
        editoptions: {
            rows: "10",
            cols: "100"
        },
        editrules: {
            custom: true,
            custom_func: function (val, colname) {
                val = tinymce.get("ShortDescription").getContent();
                if (!val) return [false, colname + ": Обязательное поле"];
                if (val.length > 500) return [false, colname + ": Длина не должна превышать 500 символов(" + val.length + ")"];
                return [true, ""];
            },
            edithidden: true
        },
        search: false
    });

    columns.push({
        name: 'Description',
        index: 'Description',
        width: 250,
        editable: true,
        sortable: false,
        hidden: true,
        edittype: 'textarea',
        editoptions: {
            rows: "40",
            cols: "100"
        },
        editrules: {
            custom: true,
            custom_func: function (val, colname) {
                val = tinymce.get("Description").getContent();
                if (val) return [true, ""];
                return [false, colname + ": Обязательное поле"];
            },
            edithidden: true
        },
        search: false
    });

    columns.push({
        name: 'Meta',
        index: 'Meta',
        width: 250,
        editable: true,
        sortable: false,
        edittype: 'textarea',
        editoptions: {
            rows: "10",
            cols: "100"
        },
        search: false
    });

    $(gridName).jqGrid({
      url: './Admin/Hikes',
      datatype: 'json',
      mtype: 'GET',
      height: 'auto',
      toppager: true,

      colNames: colNames,
      colModel: columns,

      pager: pagerName,
      rownumbers: true,
      rownumWidth: 40,
      rowNum: 10,
      rowList: [10, 20, 30],

      sortname: 'StartDate',
      sortorder: 'desc',
      viewrecords: true,

      jsonReader: {
        repeatitems: false
      },

      afterInsertRow: function (rowid, rowdata, rowelem) {
        var published = rowdata["Published"];

        if (!published) {
            $(gridName).setRowData(rowid, [], {
                color: '#9D9687'
            });
            $(gridName + " tr#" + rowid + " a").css({
                color: '#9D9687'
            });
        }
      }
    });

    // configuring add options
    var addOptions = {
      url: './Admin/AddHike',
      addCaption: 'Добавить поход',
      processData: "Сохранение...",
      width: 900,
      closeAfterAdd: true,
      closeOnEscape: true,
      afterclickPgButtons: afterclickPgButtons,
      afterShowForm: afterShowForm,
      onClose: onClose,
      afterSubmit: Romantics.GridManager.afterSubmitHandler,
      beforeSubmit: beforeSubmitHandler
    };

    var editOptions = {
      url: './Admin/EditHike',
      editCaption: 'Редактировать поход',
      processData: "Сохранение...",
      width: 900,
      closeAfterEdit: true,
      closeOnEscape: true,
      afterclickPgButtons: afterclickPgButtons,
      afterShowForm: afterShowForm,
      onClose: onClose,
      afterSubmit: Romantics.GridManager.afterSubmitHandler,
      beforeSubmit: beforeSubmitHandler
    };

    var deleteOptions = {
      url: './Admin/DeleteHike',
      caption: 'Удалить поход',
      processData: "Сохранение...",
      msg: "Удалить поход?",
      closeOnEscape: true,
      afterSubmit: Romantics.GridManager.afterSubmitHandler
    };

    $(gridName).navGrid(pagerName, { cloneToTop: true, search: false }, editOptions, addOptions, deleteOptions);
    $(gridName).filterToolbar({ searchOnEnter: false });
  };

  //************************* REPORTS GRID
  Romantics.GridManager.reportsGrid = function (gridName, pagerName) {

      //*** Event handlers
      var afterclickPgButtons = function (whichbutton, formid, rowid) {
          tinymce.get("Body").setContent(formid[0]["Body"].value);
      };

      var afterShowForm = function (form) {
          tinymce.EditorManager.execCommand('mceAddEditor', true, "Body");
      };

      var onClose = function (form) {
          tinymce.EditorManager.execCommand('mceRemoveEditor', false, "Body");
      };

      var beforeSubmitHandler = function (postdata, form) {
          postdata.Body = tinymce.get("Body").getContent();
          return [true];
      };

      var colNames = [
          'Идентификатор',
          'Имя',
          'Поход',
          'Поход',
          'Опубликован',
          'Отчет',
          'Ключевые слова'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'Name',
          index: 'Name',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'Hike.ID',
          hidden: true,
          editable: true,
          edittype: 'select',
          editoptions: {
              style: 'width:240px;',
              class: "FormElement ui-widget-content ui-corner-all",
              dataUrl: './Admin/GetHikesHtml'
          },
          editrules: {
              required: true,
              edithidden: true
          }
      });

      columns.push({
          name: 'Hike.Name',
          index: 'Hike',
          width: 150
      });

      columns.push({
          name: 'Published',
          index: 'Published',
          width: 100,
          align: 'center',
          editable: true,
          edittype: 'checkbox',
          editoptions: {
              value: "true:false",
              defaultValue: 'false'
          },
          search: false
      });

      columns.push({
          name: 'Body',
          index: 'Body',
          width: 250,
          editable: true,
          sortable: false,
          hidden: true,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          editrules: {
              custom: true,
              custom_func: function (val, colname) {
                  val = tinymce.get("Body").getContent();
                  if (!val) return [false, colname + ": Обязательное поле"];
                  return [true, ""];
              },
              edithidden: true
          },
          search: false
      });

      columns.push({
          name: 'Meta',
          index: 'Meta',
          width: 250,
          editable: true,
          sortable: false,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          search: false
      });

      $(gridName).jqGrid({
          url: './Admin/Reports',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10, 20, 30],

          sortname: 'Name',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          },

          afterInsertRow: function (rowid, rowdata, rowelem) {
              var published = rowdata["Published"];

              if (!published) {
                  $(gridName).setRowData(rowid, [], {
                      color: '#9D9687'
                  });
                  $(gridName + " tr#" + rowid + " a").css({
                      color: '#9D9687'
                  });
              }
          }
      });

      // configuring add options
      var addOptions = {
          url: './Admin/AddReport',
          addCaption: 'Добавить отчет',
          processData: "Сохранение...",
          width: 900,
          closeAfterAdd: true,
          closeOnEscape: true,
          afterclickPgButtons: afterclickPgButtons,
          afterShowForm: afterShowForm,
          onClose: onClose,
          afterSubmit: Romantics.GridManager.afterSubmitHandler,
          beforeSubmit: beforeSubmitHandler
      };

      var editOptions = {
          url: './Admin/EditReport',
          editCaption: 'Редактировать отчет',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterclickPgButtons: afterclickPgButtons,
          afterShowForm: afterShowForm,
          onClose: onClose,
          afterSubmit: Romantics.GridManager.afterSubmitHandler,
          beforeSubmit: beforeSubmitHandler
      };

      var deleteOptions = {
          url: './Admin/DeleteReport',
          caption: 'Удалить отчет',
          processData: "Сохранение...",
          msg: "Удалить отчет?",
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false }, editOptions, addOptions, deleteOptions);
      $(gridName).filterToolbar({ searchOnEnter: false });
  };

  //************************* CATEGORIES GRID
  Romantics.GridManager.categoriesGrid = function (gridName, pagerName) {
      var colNames = [
          'Идентификатор',
          'Имя',
          'URL'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'Name',
          index: 'Name',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'URL',
          index: 'URL',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          },
          search: false
      });

      $(gridName).jqGrid({
          url: './Admin/Categories',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10, 20, 30],

          sortname: 'Name',
          sortorder: 'asc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          }
      });

      var addOptions = {
          url: './Admin/AddCategory',
          addCaption: 'Добавить категорию',
          processData: "Сохранение...",
          width: 900,
          closeAfterAdd: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      var editOptions = {
          url: './Admin/EditCategory',
          editCaption: 'Редактировать категорию',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      var deleteOptions = {
          url: './Admin/DeleteCategory',
          caption: 'Удалить категорию',
          processData: "Сохранение...",
          msg: "Удалить категорию?",
          closeOnEscape: true
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false }, editOptions, addOptions, deleteOptions);
     // $(gridName).filterToolbar({ searchOnEnter: false });
  };

  //************************* REGIONS GRID
  Romantics.GridManager.regionsGrid = function (gridName, pagerName) {
    var colNames = [
        'Идентификатор',
        'Имя',
        'Страна',
        'Страна',
        'URL',
        'Ключевые слова'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'Name',
          index: 'Name',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'Country.ID',
          hidden: true,
          editable: true,
          edittype: 'select',
          editoptions: {
              style: 'width:240px;',
              class: "FormElement ui-widget-content ui-corner-all",
              dataUrl: './Admin/GetCountriesHtml'
          },
          editrules: {
              required: true,
              edithidden: true
          }
      });

      columns.push({
          name: 'Country.Name',
          index: 'Country',
          width: 150
      });

      columns.push({
          name: 'URL',
          index: 'URL',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          },
          search: false
      });

      columns.push({
          name: 'Meta',
          index: 'Meta',
          width: 250,
          editable: true,
          sortable: false,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          search: false
      });

      $(gridName).jqGrid({
          url: './Admin/Regions',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10, 20, 30],

          sortname: 'URL',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          }
      });

      var addOptions = {
          url: './Admin/AddRegion',
          addCaption: 'Добавить регион',
          processData: "Сохранение...",
          width: 900,
          closeAfterAdd: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      var editOptions = {
          url: './Admin/EditRegion',
          editCaption: 'Редактировать регион',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      var deleteOptions = {
          url: './Admin/DeleteRegion',
          caption: 'Удалить регион',
          processData: "Сохранение...",
          msg: "Удалить регион?",
          closeOnEscape: true
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false }, editOptions, addOptions, deleteOptions);
      $(gridName).filterToolbar({searchOnEnter:false});
  };

  //************************* COUNTRIES GRID
  Romantics.GridManager.countriesGrid = function (gridName, pagerName) {
      var colNames = [
        'Идентификатор',
        'Имя',
        'URL'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'Name',
          index: 'Name',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'URL',
          index: 'URL',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          },
          search:false
      });

      $(gridName).jqGrid({
          url: './Admin/Countries',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10, 20, 30],

          sortname: 'URL',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          }
      });

      var addOptions = {
          url: './Admin/AddCountry',
          addCaption: 'Добавить страну',
          processData: "Сохранение...",
          width: 900,
          closeAfterAdd: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      var editOptions = {
          url: './Admin/EditCountry',
          editCaption: 'Редактировать страну',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      var deleteOptions = {
          url: './Admin/DeleteCountry',
          caption: 'Удалить страну',
          processData: "Сохранение...",
          msg: "Удалить страну?",
          closeOnEscape: true
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false }, editOptions, addOptions, deleteOptions);
      $(gridName).filterToolbar({searchOnEnter:false});
  };

  //************************* PHOTO ALBUMS GRID
  Romantics.GridManager.photoAlbumsGrid = function (gridName, pagerName) {//*** Event handlers
      var afterclickPgButtons = function (whichbutton, formid, rowid) {
          tinymce.get("Description").setContent(formid[0]["Description"].value);
      };

      var afterShowForm = function (form) {
          tinymce.EditorManager.execCommand('mceAddEditor', true, "Description");
      };

      var onClose = function (form) {
          tinymce.EditorManager.execCommand('mceRemoveEditor', false, "Description");
      };

      var beforeSubmitHandler = function (postdata, form) {
          postdata.Description = tinymce.get("Description").getContent();
          return [true];
      };

      var colNames = [
          'Идентификатор',
          'Имя',
          'Поход',
          'Поход',
          'Опубликован',
          'Описание',
          'Фотографии',
          'Ключевые слова'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'Name',
          index: 'Name',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'Hike.ID',
          hidden: true,
          editable: true,
          edittype: 'select',
          editoptions: {
              style: 'width:240px;',
              class: "FormElement ui-widget-content ui-corner-all",
              dataUrl: './Admin/GetHikesHtml'
          },
          editrules: {
              required: true,
              edithidden: true
          }
      });

      columns.push({
          name: 'Hike.Name',
          index: 'Hike',
          width: 150
      });

      columns.push({
          name: 'Published',
          index: 'Published',
          width: 100,
          align: 'center',
          editable: true,
          edittype: 'checkbox',
          editoptions: {
              value: "true:false",
              defaultValue: 'false'
          },
          search: false
      });

      columns.push({
          name: 'Description',
          index: 'Description',
          width: 250,
          editable: true,
          sortable: false,
          hidden: true,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          editrules: {
              custom: true,
              custom_func: function (val, colname) {
                  return [true, ""];
              },
              edithidden: true
          },
          search: false
      });

      columns.push({
          name: 'Links',
          index: 'Links',
          width: 250,
          editable: true,
          sortable: false,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          search: false
      });

      columns.push({
          name: 'Meta',
          index: 'Meta',
          width: 250,
          editable: true,
          sortable: false,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          search: false
      });

      $(gridName).jqGrid({
          url: './Admin/PhotoAlbums',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10, 20, 30],

          sortname: 'Name',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          },

          afterInsertRow: function (rowid, rowdata, rowelem) {
              var published = rowdata["Published"];

              if (!published) {
                  $(gridName).setRowData(rowid, [], {
                      color: '#9D9687'
                  });
                  $(gridName + " tr#" + rowid + " a").css({
                      color: '#9D9687'
                  });
              }
          }
      });

      // configuring add options
      var addOptions = {
          url: './Admin/AddPhotoAlbum',
          addCaption: 'Добавить альбом',
          processData: "Сохранение...",
          width: 900,
          closeAfterAdd: true,
          closeOnEscape: true,
          afterclickPgButtons: afterclickPgButtons,
          afterShowForm: afterShowForm,
          onClose: onClose,
          afterSubmit: Romantics.GridManager.afterSubmitHandler,
          beforeSubmit: beforeSubmitHandler
      };

      var editOptions = {
          url: './Admin/EditPhotoAlbum',
          editCaption: 'Редактировать альбом',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterclickPgButtons: afterclickPgButtons,
          afterShowForm: afterShowForm,
          onClose: onClose,
          afterSubmit: Romantics.GridManager.afterSubmitHandler,
          beforeSubmit: beforeSubmitHandler
      };

      var deleteOptions = {
          url: './Admin/DeletePhotoAlbum',
          caption: 'Удалить альбом',
          processData: "Сохранение...",
          msg: "Удалить альбом?",
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false }, editOptions, addOptions, deleteOptions);
      $(gridName).filterToolbar({ searchOnEnter: false });
  };

  //************************* MAIN PAGE GRID
  Romantics.GridManager.mainPageGrid = function (gridName, pagerName) {

      //*** Event handlers
      var afterShowForm = function (form) {
          tinymce.EditorManager.execCommand('mceAddEditor', true, "MainPage");
      };

      var onClose = function (form) {
          tinymce.EditorManager.execCommand('mceRemoveEditor', false, "MainPage");
      };

      var beforeSubmitHandler = function (postdata, form) {
          postdata.MainPage = tinymce.get("MainPage").getContent();
          return [true];
      };

      var colNames = [
          'Идентификатор',
          'Главная страница',
          'Домен для DISQUS',
          'URL для Add This',
          'Авторы',
          'Meta Description',
          'Meta Keywords'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'MainPage',
          index: 'MainPage',
          width: 250,
          editable: true,
          sortable: false,
          hidden: true,
          edittype: 'textarea',
          editoptions: {
              rows: "40",
              cols: "100"
          },
          editrules: {
              custom: true,
              custom_func: function (val, colname) {
                  val = tinymce.get("MainPage").getContent();
                  if (val) return [true, ""];
                  return [false, colname + ": Обязательное поле"];
              },
              edithidden: true
          },
          search: false
      });

      columns.push({
          name: 'DisqusDomain',
          index: 'DisqusDomain',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'AddThisURL',
          index: 'AddThisURL',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'Author',
          index: 'Author',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'MetaDescription',
          index: 'MetaDescription',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'MetaKeywords',
          index: 'MetaKeywords',
          width: 250,
          editable: true,
          sortable: false,
          edittype: 'textarea',
          editoptions: {
              rows: "10",
              cols: "100"
          },
          search: false
      });

      $(gridName).jqGrid({
          url: './Admin/Options',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10],

          sortname: 'ID',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          }
      });

      var editOptions = {
          url: './Admin/EditMainPageOptions',
          editCaption: 'Редактировать опции',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterShowForm: afterShowForm,
          onClose: onClose,
          afterSubmit: Romantics.GridManager.afterSubmitHandler,
          beforeSubmit: beforeSubmitHandler
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false, del: false, add: false, edit: true }, editOptions, {}, {});
  };

  //************************* CONTACT INFO GRID
  Romantics.GridManager.contactInfoGrid = function (gridName, pagerName) {

      var colNames = [
          'Идентификатор',
          'Email Администратора',
          'Телефон №1',
          'Имя №1',
          'Телефон №2',
          'Имя №2',
          'Телефон №3',
          'Имя №3'
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'AdminEmail',
          index: 'AdminEmail',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'ContactPhone1',
          index: 'ContactPhone1',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'ContactName1',
          index: 'ContactName1',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'ContactPhone2',
          index: 'ContactPhone2',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'ContactName2',
          index: 'ContactName2',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'ContactPhone3',
          index: 'ContactPhone3',
          width: 250,

          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      columns.push({
          name: 'ContactName3',
          index: 'ContactName3',
          width: 250,

          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          }
      });

      $(gridName).jqGrid({
          url: './Admin/Options',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10],

          sortname: 'ID',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          }
      });

      var editOptions = {
          url: './Admin/EditContacOptions',
          editCaption: 'Редактировать опции',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false, del: false, add: false, edit: true }, editOptions, {}, {});
  };

  //************************* SMTP GRID
  Romantics.GridManager.smtpSettingsGrid = function (gridName, pagerName) {

      var colNames = [
          'Идентификатор',
          'SMTP Сервер',
          'SMTP Порт',
          'Имя пользователя (SMTP)',
          'Пароль (SMTP)',
      ];

      var columns = [];

      columns.push({
          name: 'ID',
          hidden: true,
          key: true
      });

      columns.push({
          name: 'SMPT_Server',
          index: 'SMPT_Server',
          width: 250,
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'SMPT_Port',
          index: 'SMPT_Port',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200,
              edithidden:true
          },
          editrules: {
              integer: true,
              required: true
          }
      });

      columns.push({
          name: 'SMPT_UserName',
          index: 'SMPT_UserName',
          width: 250,
          
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200,
              edithidden: true
          },
          editrules: {
              required: true
          }
      });

      columns.push({
          name: 'SMPT_Password',
          index: 'SMPT_Password',
          width: 250,
          
          edittype: 'password',
          editable: true,
          editoptions: {
              size: 43,
              maxlength: 200,
              edithidden: true
          },
          editrules: {
              required: true
          }
      });

      $(gridName).jqGrid({
          url: './Admin/Options',
          datatype: 'json',
          mtype: 'GET',
          height: 'auto',
          toppager: true,

          colNames: colNames,
          colModel: columns,

          pager: pagerName,
          rownumbers: true,
          rownumWidth: 40,
          rowNum: 10,
          rowList: [10],

          sortname: 'ContactPhone2',
          sortorder: 'desc',
          viewrecords: true,

          jsonReader: {
              repeatitems: false
          }
      });

      var editOptions = {
          url: './Admin/EditSmtpOptions',
          editCaption: 'Редактировать опции',
          processData: "Сохранение...",
          width: 900,
          closeAfterEdit: true,
          closeOnEscape: true,
          afterSubmit: Romantics.GridManager.afterSubmitHandler
      };

      $(gridName).navGrid(pagerName, { cloneToTop: true, search: false, del: false, add: false, edit:true}, editOptions, {}, {});
  };

  Romantics.GridManager.afterSubmitHandler = function (response, postdata) {

    var json = $.parseJSON(response.responseText);

    if (json) return [json.success, json.message, json.id];

    return [false, "Failed to get result from server.", null];
  };

  $("#tabs").tabs({
    show: function (event, ui) {

      if (!ui.tab.isLoaded) {

        var gdMgr = Romantics.GridManager,
                fn, gridName, pagerName;

        switch (ui.index) {
          case 0:
            fn = gdMgr.hikesGrid;
            gridName = "#tableHikes";
            pagerName = "#pagerHikes";
            break;
        case 1:
            fn = gdMgr.reportsGrid;
            gridName = "#tableReports";
            pagerName = "#pagerReports";
            break;
        case 2:
            fn = gdMgr.photoAlbumsGrid;
            gridName = "#tablePhotoAlbums";
            pagerName = "#pagerPhotoAlbums";
            break;
        case 3:
            fn = gdMgr.photosGrid;
            gridName = "#tablePhotos";
            pagerName = "#pagerPhotos";
            break;
        case 4:
            fn = gdMgr.categoriesGrid;
            gridName = "#tableCategories";
            pagerName = "#pagerCategories";
            break;
        case 5:
            fn = gdMgr.regionsGrid;
            gridName = "#tableRegions";
            pagerName = "#pagerRegions";
            break;
        case 6:
            fn = gdMgr.countriesGrid;
            gridName = "#tableCountries";
            pagerName = "#pagerCountries";
            break;
        case 7:
            fn = gdMgr.mainPageGrid;
            gridName = "#tableMainPage";
            pagerName = "#pagerMainPage";
            break;
        case 8:
            fn = gdMgr.contactInfoGrid;
            gridName = "#tableContactInfo";
            pagerName = "#pagerContactInfo";
            break;
        case 9:
            fn = gdMgr.smtpSettingsGrid;
            gridName = "#tableSmtpSettings";
            pagerName = "#pagerSmtpSettings";
            break;
        };

        fn(gridName, pagerName);
        ui.tab.isLoaded = true;
      }
    }
  });
});